﻿using CommonLibrary.Helper;
using CommonLibrary.Pools;

using DataModel.Contants;
using DataModel.Models;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

using static CommonLibrary.Pools.PictureDownloadPool;

namespace CuteWallpaperDemo.Managers
{
    /// <summary>
    /// 壁纸管理器（已过时）
    /// </summary>
    public class WallpaperManager
    {
        /// <summary>
        /// 设置壁纸到桌面
        /// </summary>
        /// <param name="path"></param>
        public void SetWallpaper(string path)
        {
            DllImportHelper.SystemParametersInfoA(WinMessages.SPI_SETDESKWALLPAPER, 0, path, 1);
        }

        /// <summary>
        /// 设置提示框消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="title"></param>
        public void SetMessageBox(string message, string? title = null)
        {
            message = message ?? string.Empty;
            title = title ?? string.Empty;

            Application.Current.Dispatcher.Invoke(() =>
            {
                MessageBox.Show(message, title);
            });
        }

        /// <summary>
        /// 扫描壁纸资源文件夹
        /// </summary>
        /// <returns></returns>
        public IList<WallpaperInfo> OnScanCache()
        {
            string cache = DomainHelper.GetWallpaperPath();
            string[] dirs = Directory.GetDirectories(cache);
            return ScanWallpapers(dirs);
        }

        /// <summary>
        /// 扫描播放列表
        /// </summary>
        /// <returns></returns>
        public IList<WallpaperInfo> OnScanPlaylist()
        {
            string[] dirs = ConfigManager.Instance.PlayList.Wallpapaers;
            return ScanWallpapers(dirs);
        }

        public void SaveProject(Project project)
        {
            string path = Path.Combine(project.Dir, "project.json");
            JsonHelper.SaveToJson(ref project, path);
        }

        public static WallpaperInfo ProjectToInfo(Project project)
        {
            return new WallpaperInfo
            {
                Title = project.Title,
                Path = Path.Combine(project.Dir, project.Path),
                PreviewPath = Path.Combine(project.Dir, project.Middle),
                IconPath = Path.Combine(project.Dir, project.Preview),
                OriginPath = Path.Combine(project.Dir, project.Origin),
                Dir = project.Dir,
            };
        }

        public async static Task<WallpaperInfo> ProjectToInfoAsync(Project project)
        {
            var info = ProjectToInfo(project);
            try
            {
                BitmapImage bitmap = await PictureHelper.LoadImageAsync(Path.Combine(project.Dir, project.Origin));
                info.Width = bitmap.PixelWidth;
                info.Height = bitmap.PixelHeight;
            }
            catch
            {

            }
            return info;
        }

        public static bool CheckWallpaperExists(WallpaperInfo? info)
        {
            if (info == null) return false;
            if (!Directory.Exists(info.Dir)) return false;
            if (!File.Exists(info.Path)) return false;
            if (!File.Exists(info.PreviewPath)) return false;
            if (!File.Exists(info.IconPath)) return false;
            return true;
        }

        /// <summary>
        /// 获取目录下的所有壁纸
        /// </summary>
        /// <param name="dirs"></param>
        /// <returns></returns>
        private static IList<WallpaperInfo> ScanWallpapers(string[] dirs)
        {
            IList<WallpaperInfo> list = new List<WallpaperInfo>(dirs.Length);
            foreach (string dir in dirs)
            {
                if (!Directory.Exists(dir)) continue;
                var path = Path.Combine(dir, "project.json");
                if (!File.Exists(path)) continue;

                JsonHelper.ReadJson(dir + "/project.json", out Project? project);
                if (project == null) continue;
                project.Dir = dir;

                var info = ProjectToInfo(project);
                if (!CheckWallpaperExists(info)) continue;

                list.Add(info);
            }
            return list;
        }

    }

    /// <summary>
    /// 壁纸管理器
    /// </summary>
    public static class NewWallpaperManager
    {
        /// <summary>
        /// 设置桌面壁纸
        /// </summary>
        /// <param name="url"></param>
        public static void SetWallpaper(string url)
        {
            string cachePath = DomainHelper.GetCachedFilePath(url);
            DllImportHelper.SystemParametersInfoA(WinMessages.SPI_SETDESKWALLPAPER, 0, cachePath, 1);
        }

        /// <summary>
        /// 扫描壁纸
        /// </summary>
        /// <returns></returns>
        public static void ScanWallpapers(Action callback)
        {
            string[] objs = GetWallpaperList();
            ConfigManager.Instance.WallpaperIndex.Wallpapaers = objs;
            IList<string> caches = [];

            foreach (var url in objs)
            {
                string cachePath = DomainHelper.GetCachedFilePath(url);
                if (!File.Exists(cachePath))
                {
                    caches.Add(url);
                }
            }

            if (caches.Count == 0)
            {
                // 通知
                callback();
                return;
            }

            // 从服务器下载

            // 同步下载
            //foreach (var cache in caches)
            //{
            //    OssHelper.GetObject(AppDefines.OssConfig, cache);
            //}

            // 异步下载
            PictureDownloadPool.Downloads([.. caches], result =>
            {
                if (result.Error == null)
                {
                    // 通知
                    callback();
                }
            });
        }

        /// <summary>
        /// 获取壁纸列表
        /// </summary>
        /// <returns></returns>
        public static string[] GetWallpaperList()
        {
            return OssHelper.ListObject(AppDefines.OssConfig) ?? [];
        }

        /// <summary>
        /// 上传壁纸
        /// </summary>
        /// <param name="objs"></param>
        /// <returns>上传失败数量</returns>
        public static int UploadWallpaper(string[] objs)
        {
            int errCount = 0;
            foreach (var obj in objs)
            {
                //GeneralTask task = new GeneralTask(() =>
                //{
                //    OssHelper.PutObject(AppDefines.OssConfig, obj.Trim());
                //});

                //ThreadPoolFactory.AdvancedPoolHandler.EnqueueTask(task);

                var res = OssHelper.PutObject(AppDefines.OssConfig, obj.Trim());
                if (!res)
                {
                    errCount++;
                }
            }

            return errCount;
        }

        /// <summary>
        /// 读取原图
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static BitmapImage? GetOrigin(string path)
        {
            return PictureHelper.CreateImage(path);
        }

        /// <summary>
        /// 读取中等质量图片
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static BitmapImage? GetMiddle(string path)
        {
            return PictureHelper.CreateImage(path, 960);
        }

        /// <summary>
        /// 读取低分辨预览图
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static BitmapImage? GetPreview(string path)
        {
            return PictureHelper.CreateImage(path, 200);
        }

        public static BitmapImage? GetFromUri(string path)
        {
            return new BitmapImage(new Uri(path));
        }
    }
}
